package com.mlz.mlzmall.ui.activity.act.personal;

import android.app.Activity;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.JsonRequest;
import com.google.gson.Gson;
import com.mlz.mlzmall.R;
import com.mlz.mlzmall.bean.StatusBean;
import com.mlz.mlzmall.ui.activity.act.address.postCodeToPCD;
import com.mlz.mlzmall.ui.activity.act.base.TopTitleView;
import com.mlz.mlzmall.ui.activity.act.main.MyApplication;
import com.mlz.mlzmall.ui.activity.act.personal.NetworkRequest.VolleyBaseActivity;
import com.mlz.mlzmall.ui.adapter.base.MallHolder;
import com.mlz.mlzmall.ui.adapter.base.ShopMallAdapter;
import com.mlz.mlzmall.ui.model.AddressAllTagBean;
import com.mlz.mlzmall.ui.utils.mlz.ConfigInfo;
import com.mlz.mlzmall.ui.utils.mlz.URL;
import com.mlz.mlzmall.ui.utils.util.LogUtils;
import com.mlz.mlzmall.ui.utils.util.ScreenUtils;
import com.mlz.mlzmall.ui.utils.vali.PhoneValidate;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * Created by yhf on 2016/5/18.
 */
public class ChangeAddress extends VolleyBaseActivity {

    private EditText tvReceiverName;//收货人
    private EditText tvDetailAddress;//详细收货地址
    private EditText tvPhoneNumber;//联系方式
    private CheckBox cbDefaultAddress;//是否设置默认地址
    private Button btnDeleteAddress;//删除地址
    private Button btnSaveAddress;//保存地址按钮
    private String userName;//收货人
    private String phoneNumber;//电话
    private String address;//地址
    private int regionCode;
    private Boolean defaultAddress;
    private int addressId;//地址ID
    private List<AddressAllTagBean.ProvinceBean> province;
    private List<AddressAllTagBean.ProvinceBean.CityBean> city = new ArrayList<AddressAllTagBean.ProvinceBean.CityBean>();
    private List<AddressAllTagBean.ProvinceBean.CityBean.AreaBean> area = new ArrayList<AddressAllTagBean.ProvinceBean.CityBean.AreaBean>();
    private static View pw;
    private static ListView listView;
    private static PopupWindow pWindow;
    private TextView tv_area;
    private TextView tv_city;
    private TextView tv_province;
    private StringBuilder builder;
    private AddressAllTagBean ab;
    private String s_province;
    private String s_city;
    private String s_area;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.add_new_address);//修改地址的布局
        setViewContent();
        initView();
        getData();//获取原地址的数据
    }
    private void setViewContent() {
        TopTitleView loginTopTitle = (TopTitleView) findViewById(R.id.login_top_title);
        loginTopTitle.setLeftButtonContent(null, R.mipmap.pic_2_1_btn_back, null);
        loginTopTitle.setTitleButtonContent("修改地址", null, null);
        loginTopTitle.setOnLeftButtonClickListener(new TopTitleView.OnLeftButtonClickListener() {
            @Override
            public void onLeftBtnClick(View button) {
                finish();
                ChangeAddress.this.overridePendingTransition(R.anim.right_in,R.anim.right_out);
            }
        });
    }



    private void getData() {
        userName = getIntent().getStringExtra("FullName");//收获人
        phoneNumber = getIntent().getStringExtra("Telephone");//电话
        address = getIntent().getStringExtra("Address");//地址
        defaultAddress = getIntent().getBooleanExtra("DefaultAddress", true);
        regionCode = getIntent().getIntExtra("RegionCode", 0);
        addressId = getIntent().getIntExtra("AddressId", 0);
        postCodeToPCD ppp=new postCodeToPCD(this);//获取省市县
        tv_province.setText(ppp.province(regionCode+""));
        tv_city.setText(ppp.city(regionCode+""));
        tv_area.setText(ppp.district(regionCode+""));
        tvReceiverName.setText(userName);
        tvReceiverName.setSelection(tvReceiverName.length());//定位光标
        tvDetailAddress.setText(address);
        tvDetailAddress.setSelection(tvDetailAddress.length());
        tvPhoneNumber.setText(phoneNumber);
        tvPhoneNumber.setSelection(tvPhoneNumber.length());
        if (defaultAddress == true) {
            cbDefaultAddress.setChecked(true);
        }
        tvReceiverName.setSelection(tvReceiverName.getText().length());
        tvDetailAddress.setSelection(tvDetailAddress.getText().length());
        tvPhoneNumber.setSelection(tvPhoneNumber.getText().length());
    }

    private void initView() {
        tvReceiverName = (EditText) findViewById(R.id.tv_receiver_name);
        tvDetailAddress = (EditText) findViewById(R.id.tv_detail_address);
        tvPhoneNumber = (EditText) findViewById(R.id.tv_phone_number);
        tv_province = (TextView) findViewById(R.id.tv_province);
        tv_city = (TextView) findViewById(R.id.tv_city);
        tv_area = (TextView) findViewById(R.id.tv_area);
        cbDefaultAddress = (CheckBox) findViewById(R.id.cb_default_address);
        btnDeleteAddress = (Button) findViewById(R.id.btn_delete_address);
        btnSaveAddress = (Button) findViewById(R.id.btn_save_address);
        btnDeleteAddress.setOnClickListener(this);
        btnSaveAddress.setOnClickListener(this);
        tv_province.setOnClickListener(this);
        tv_city.setOnClickListener(this);
        tv_area.setOnClickListener(this);
        btnDeleteAddress.setVisibility(View.VISIBLE);
        cbDefaultAddress.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                defaultAddress = isChecked;
            }
        });
    }

    private void getPostCode(String str) {
        Gson gson = new Gson();
        ab = gson.fromJson(str, AddressAllTagBean.class);
        province = ab.getProvince();
    }

    private String ReadStringJson() {
        try {
            InputStreamReader isr = new InputStreamReader(ChangeAddress.this.getAssets().open("postcode.json"), "UTF-8");
            BufferedReader br = new BufferedReader(isr);
            String line;
            builder = new StringBuilder();//读取数据到StringBuilder中
            while ((line = br.readLine()) != null) {
                builder.append(line);
            }
            br.close();
            isr.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        LogUtils.d(builder.toString());
        return builder.toString();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_delete_address://删除地址的监听,地址listView的条目消失(获取到addressId，删除即可)
                delAddress(addressId);
                break;

            case R.id.btn_save_address://保存修改后的地址
                //将数据上传服务器,返回上一层
                sendPost();
                break;

            case R.id.tv_province:
                getPostCode(ReadStringJson());
                setAddress(1, tv_province);
                tv_city.setText("");
                tv_area.setText("");
                break;
            case R.id.tv_city:
                setAddress(2, tv_city);
                tv_area.setText("");
                break;
            case R.id.tv_area:
                setAddress(3, tv_area);
                break;

        }
    }

    private void sendPost() {
        userName = tvReceiverName.getText().toString();
        phoneNumber = tvPhoneNumber.getText().toString();
        address = tvDetailAddress.getText().toString();
        s_province = tv_province.getText().toString();
        s_city = tv_city.getText().toString();
        s_area = tv_area.getText().toString();
        if (userName.length() == 0 || phoneNumber.length() == 0 || address.length() == 0 || s_province.length() == 0 || s_city.length() == 0 || s_area.length() == 0) {
            showToast("请将信息填写完整");
        } else if (!PhoneValidate.isPhone(phoneNumber)) {
            showToast("手机号格式不正确");
        } else {
            postEditAddress(userName, phoneNumber, address, regionCode, defaultAddress, addressId);
        }
    }


    public void setAddress(final int iii, final TextView tv) {
        //  退出对话框
        pw = LayoutInflater.from(ChangeAddress.this).inflate(R.layout.dialog_list, null);
        listView = (ListView) pw.findViewById(R.id.listView);
        if (iii == 1) {
            ProvinceAdapter adapter = new ProvinceAdapter(this, province, R.layout.spinner_display_style);
            listView.setAdapter(adapter);
        }
        if (iii == 2) {
            CityAdapter adapter = new CityAdapter(this, city, R.layout.spinner_display_style);
            listView.setAdapter(adapter);
        }
        if (iii == 3) {
            AreaAdapter adapter = new AreaAdapter(this, area, R.layout.spinner_display_style);
            listView.setAdapter(adapter);
        }
        pWindow = new PopupWindow(pw, tv.getWidth(), ScreenUtils.getScreenWidth(this) * 2 / 3);//弹框显示大小
        pWindow.setFocusable(true);
        pWindow.setBackgroundDrawable(new ColorDrawable(0x55000000));//设置背景为透明
        pWindow.showAsDropDown(tv);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (iii == 1) {
                    tv.setText(province.get(position).getName());
                    if (province != null || !province.isEmpty()) {
                        city = province.get(position).getCity();
                        LogUtils.d(province.get(position).getName());
                    }
                }
                if (iii == 2) {
                    tv.setText(city.get(position).getName());
                    if (city != null || !city.isEmpty()) {
                        area = city.get(position).getArea();
                        LogUtils.d(city.get(position).getName());
                    }
                }
                if (iii == 3) {
                    tv.setText(area.get(position).getName());
                    regionCode = Integer.parseInt(area.get(position).getCode());
                    if (area != null || !area.isEmpty()) {
                        LogUtils.d(area.get(position).getName());
                    }
                }
                pWindow.dismiss();
            }
        });
    }

    private class ProvinceAdapter extends ShopMallAdapter<AddressAllTagBean.ProvinceBean> {
        public ProvinceAdapter(Activity activity, List<AddressAllTagBean.ProvinceBean> list, int id_layout) {
            super(activity, list, id_layout);
        }

        @Override
        public void convert(MallHolder holder, AddressAllTagBean.ProvinceBean o) {
            holder.setText(R.id.tv_spinner, o.getName());
        }
    }

    private class CityAdapter extends ShopMallAdapter<AddressAllTagBean.ProvinceBean.CityBean> {
        public CityAdapter(Activity activity, List<AddressAllTagBean.ProvinceBean.CityBean> list, int id_layout) {
            super(activity, list, id_layout);
        }

        @Override
        public void convert(MallHolder holder, AddressAllTagBean.ProvinceBean.CityBean o) {
            holder.setText(R.id.tv_spinner, o.getName());
        }
    }

    private class AreaAdapter extends ShopMallAdapter<AddressAllTagBean.ProvinceBean.CityBean.AreaBean> {
        public AreaAdapter(Activity activity, List<AddressAllTagBean.ProvinceBean.CityBean.AreaBean> list, int id_layout) {
            super(activity, list, id_layout);
        }

        @Override
        public void convert(MallHolder holder, AddressAllTagBean.ProvinceBean.CityBean.AreaBean o) {
            holder.setText(R.id.tv_spinner, o.getName());
        }
    }

    private void delAddress(int addressId) {
        Map<String, String> param1 = new HashMap<String, String>();
        param1.put("addressId", addressId + "");
        JSONObject jsonObject = new JSONObject(param1);
        JsonRequest jsonRequest = new JsonObjectRequest(Request.Method.POST, URL.ADDRESS.REMOVE, jsonObject, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                Log.e(tag, jsonObject.toString());
                Gson gson = new Gson();
                StatusBean sb = gson.fromJson(jsonObject.toString(), StatusBean.class);
                if (sb.getStatus() == 0) {
                    showToast(sb.getMsg());
                    finish();
                    ChangeAddress.this.overridePendingTransition(R.anim.right_in, R.anim.right_out);
                } else {
                    showToast(sb.getMsg());
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e(tag, error.getMessage(), error);
            }
        }) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                map.put(ConfigInfo.CHARSET, ConfigInfo.UTF8);
                map.put(ConfigInfo.COOKIE, ConfigInfo.COOKIE_KEY + sessionId);
                map.put(ConfigInfo.TYPE, ConfigInfo.TYPE_KEY);
                return map;
            }
        };

        // 设置该请求的标签
        jsonRequest.setTag(tag);
        // 将请求添加到队列中
        ((MyApplication) getApplication()).getRequestQueue().add(jsonRequest);

    }

    //添加地址
    private void postEditAddress(String userName, String phoneNumber, String address, int regionCode, Boolean defaultAddress, int addressId) {
        tag = "rPost";
        Map<String, String> param1 = new HashMap<String, String>();
        param1.put("fullname", isNull(userName));
        param1.put("shippingTelephone", isNull(phoneNumber));
        param1.put("address", isNull(address));
        param1.put("postcode", "");
        param1.put("regionCode", isNull(regionCode + ""));
        param1.put("defaultAddress", isNull(defaultAddress + ""));
        param1.put("addressId", isNull(addressId + ""));

        JSONObject jsonObject = new JSONObject(param1);
        JsonRequest jsonRequest = new JsonObjectRequest(Request.Method.POST, URL.ADDRESS.EDIT, jsonObject, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                LogUtils.d(jsonObject.toString());
                Gson gson = new Gson();
                StatusBean sb = gson.fromJson(jsonObject.toString(), StatusBean.class);
                if (sb.getStatus() == 0) {
                    showToast("地址修改成功");
                    finish();
                    ChangeAddress.this.overridePendingTransition(R.anim.right_in, R.anim.right_out);
                }
                else {
                    showToast(sb.getMsg());
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Log.e(tag, volleyError.getMessage(), volleyError);
            }
        }) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                map.put(ConfigInfo.CHARSET, ConfigInfo.UTF8);
                map.put(ConfigInfo.COOKIE, ConfigInfo.COOKIE_KEY + sessionId);
                map.put(ConfigInfo.TYPE, ConfigInfo.TYPE_KEY);
                return map;
            }
        };
        //设置该请求的标签
        jsonRequest.setTag(jsonRequest);
        //将请求添加到队列
        ((MyApplication) getApplication()).getRequestQueue().add(jsonRequest);
    }
}
